package ups.glre.news.service.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ups.glre.news.dao.CategoryDAO;
import ups.glre.news.model.Category;
import ups.glre.news.service.CategoryService;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@Local
public class CategoryServiceImpl implements CategoryService {
	
	@Resource
	private SessionContext sessionContext;
	
	@PersistenceContext(unitName = "PersistenceManager")
	protected EntityManager entityManager;
	
	@EJB
	private CategoryDAO categoryDAO;
	
	@Override
	public void createCategory() {
		//TODO
	}
	
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	@Override
	public void createCategory(String categoryName) {
		Category category = new Category(categoryName);
		categoryDAO.createObject(category);
	}

	@Override
	public List<Category> getAllCategory() {
		List<Category> categories = categoryDAO.findAllObject();	
		return categories;
	}
	
	@Override
	public void subscribeUserToCategory(int userId, int categoryId){
		// TODO Auto-generated method stub
		
	}

	@Override
	public void unSubscribeUserFromCategory(int userId, int categoryId) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void subscribeUserToCategory(int userId, String[] categoriesId) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void unSubscribeUserFromCategory(int userId, String[] categoriesId) {
		// TODO Auto-generated method stub
		
	}
	
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	@Override
	public void populateCategoryTables(){
		CategoryService businessObject = this.sessionContext.getBusinessObject(CategoryService.class);
		
		if (getCategoryByName("categorie1") == null)
			businessObject.createCategory("categorie1");
		
		if (getCategoryByName("categorie2") == null)
			businessObject.createCategory("categorie2");
		
		if (getCategoryByName("categorie3") == null)
			businessObject.createCategory("categorie3");
		
	}

	@Override
	public Category getCategoryByName(String categoryName) {
		Category category = null;
		try{
			category = categoryDAO.findCategoryByName(categoryName);			
		}	catch(Exception e){
			
		}		
		return category;
	}
}
